package gov.pbc.nn.kjgl.software.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import com.bstek.uflo.client.service.ProcessClient;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.model.ProcessInstance;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;
import gov.pbc.nn.kjgl.entity.ProjectFile;
import gov.pbc.nn.uflo.entity.Opinion;

@Repository
public class KjkShDao extends AbstractHibernateDao {
	@Autowired
	@Qualifier(TaskClient.BEAN_ID)
	private TaskClient taskClient;

	@Autowired
	@Qualifier(ProcessClient.BEAN_ID)
	private ProcessClient processClient;

	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao pbcnnCoreHibernateDao;

	// 查询历史表，如过有就显示（图片）
	public String[] getOpinionSign(String businessId, String processInstanceId, String taskId, String username)
			throws Exception {
		// 取流程变量
		String zgkjhld = (String) this.processClient.getProcessVariable("zgkjhld", Long.parseLong(processInstanceId));
		// 以前存在流程变量，现在保存在project表中，所以可以从前台传过来
		// String zgywhld = (String)
		// this.processClient.getProcessVariable("zgywhld",
		// Long.parseLong(processInstanceId));
		String hql = "select opinionImg from "
				+ Opinion.class.getName()
				+ " where invalid=false and busKey=:busKey and username=:username and taskId=:taskId";
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("busKey", businessId);
		map.put("username", zgkjhld);
		map.put("taskId", Long.parseLong(taskId));
		List<Object> list = this.pbcnnCoreHibernateDao.query(hql, map);
		// 查询主管行领导如果为空则 返回 null
		byte[] zgkjhldSign = (byte[]) (list.isEmpty() ? null : list.get(0));

		// 查询业务行领导如果为空则 返回 null
		map.put("username", username);
		list = this.pbcnnCoreHibernateDao.query(hql, map);
		byte[] zgywhldSign = (byte[]) (list.isEmpty() ? null : list.get(0));

		String zgkjhldSignStr = null;
		if (zgkjhldSign != null) {
			String sign = Base64.encodeBase64String(zgkjhldSign);
			zgkjhldSignStr = "data:image/jpg;base64," + sign;
		}

		String zgywhldSignStr = null;
		if (zgywhldSign != null) {
			String sign = Base64.encodeBase64String(zgywhldSign);
			zgywhldSignStr = "data:image/jpg;base64," + sign;
		}
		// 返回值一个数组 返回主管行领导和业务行领导
		String[] result = new String[2];
		result[0] = zgkjhldSignStr;
		result[1] = zgywhldSignStr;

		return result;
	}

}
